import axios from 'axios'
const Qs = require('qs') // eslint-disable-line
import { CommonJs } from '@/assets/utils/base.js'
import { Loading, Message } from 'element-ui'

const http = (option, data, loadingInstance) => {
  const thisaxios = axios.create()
  /** 请求拦截器（then前） */
  thisaxios.interceptors.request.use(config => {
    if (option.isloading === true) {
      loadingInstance = Loading.service({
        body: true,
        target: option.loadingTaeget ? option.loadingTaeget : '.loading',
        background: 'transparent'
      })
    }
    return config
  }, error => {
    return Promise.reject(error)
  })
  /** 响应拦截器（catch前） */
  thisaxios.interceptors.response.use(response => {
    try { loadingInstance.close() } catch (error) {}
    const res = response.data
    /** 成功才返回值 */
    if (option.isalert === true) {
      if (res.result !== 1) {
        Message({
          message: decodeURIComponent(res.msg),
          type: 'error',
          duration: 1 * 1000
        })
      } else {
        Message({
          message: decodeURIComponent(res.msg),
          type: 'success',
          duration: 1 * 1000
        })
      }
    }
    return response.data
  }, error => {
    return Promise.reject(error)
  })
  /** axios封装 */
  var ajaxurl = CommonJs.httpurl(option.url, option.fromwho)
  var headers = { json: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, form: { 'Content-Type': 'application/x-www-form-urlencoded' }}
  const httpDefaultOpts = {
    url: ajaxurl,
    method: option.method ? option.method : 'get', // 默认是 get
    baseURL: '',
    timeout: 100000,
    // `params` 是即将与请求一起发送的 URL 参数(get请求)
    params: Object.assign({}, data),
    // `data` 是作为请求主体被发送的数据(post请求)
    data: Object.prototype.toString.call(data) === '[object Object]' ? Qs.stringify(Object.assign({}, data)) : data,
    // `transformRequest` 允许在向服务器发送前，修改请求数据
    // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
    // 后面数组中的函数必须返回一个字符串，或 ArrayBuffer，或 Stream
    transformRequest: [function (data) {
      return data
    }]
  }
  if (option.method === 'get') {
    delete httpDefaultOpts.data
  } else {
    delete httpDefaultOpts.params
  }
  if (option.headers === 'json' && option.method === 'get') {
    httpDefaultOpts.params = JSON.stringify(Object.assign({}, data))
  }
  if (option.headers) {
    var type = option.headers
    httpDefaultOpts.headers = headers[type]
  }

  const promise = new Promise(function (resolve, reject) {
    thisaxios(httpDefaultOpts).then(
      (res) => {
        // successState(res)
        resolve(res)
      }
    ).catch(
      (err) => {
        // errorState(response)
        reject(err)
      }
    )
  })
  return promise
}
export default http
